<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2022/1/18
 * Time: 7:59 下午
 */

namespace app\api\controller\v30;

use app\api\controller\v2\Auth;
use app\common\cachemodel\Goods;
use app\common\cachemodel\live\LiveAnchorInfo;
use app\common\cachemodel\live\LiveAnswerAstroRecord;
use app\common\cachemodel\live\LiveAnswerDiceRecord;
use app\common\cachemodel\live\LiveAnswerTarotRecord;
use app\common\cachemodel\live\LiveRecordingInfo;
use app\common\cachemodel\Orders as OrdersCacheModel;
use app\common\cachemodel\OrdersLib;
use app\common\cachemodel\OrdersLib as OrdersCacheModelLib;
use app\common\cachemodel\ZlTarotRecords;
use app\common\lib\exception\ApiException;
use app\common\lib\PushQueue;
use app\common\model\Divination;
use think\Cache;
use think\Log;

/**
 * Class Orders
 */
class Orders extends Auth
{
    /**
     * 提交解答
     * @return \think\response\Json
     * @throws ApiException
     */
    public function submitAnswer()
    {
        $tradeType = input('trade_type/d', 0);
        $orderType = input('order_type/d', 0);
        $liveRecordId = input('live_record_id/d', 0);

        $cache = Cache::get('submit_answer_order:' . $this->user['id'] . ':' . $orderType);
        if ($cache === true)
        {
            throw new ApiException('操作频繁，请稍后再试', 200, 0);
        }
        Cache::set('submit_answer_order:' . $this->user['id'] . ':' . $orderType, true, 5);

        if (!in_array($tradeType, [1, 2, 4, 9], true))
        {
            return show(config('code.error'), '暂不支持此支付方式');
        }
        if (!in_array($orderType, [19, 20, 21], true))
        {
            return show(config('code.error'), '请求异常');
        }
        if (!$liveRecordId)
        {
            return show(config('code.error'), '直播间不存在');
        }
        //验证直播是否存在
        $record = (new LiveRecordingInfo())->getInfoById($liveRecordId, ['status', 'live_id']);
        if (!$record)
        {
            return show(config('code.error'), '直播间不存在');
        }
        $liveId = $record['live_id'];

        //缓存获取数据,验证记录是否存在
        $answerModel = null;
        switch ($orderType)
        {
            case 19:
                $answerModel = new LiveAnswerAstroRecord();
                $history = (new LiveAnswerAstroRecord())->getUserRequestAnswerPrepareInfo($liveId, $liveRecordId, $this->user['id']);
                if (!$history)
                {
                    Log::write('用户' . $this->user['id'] . 'astro解答申请信息未找到 - ' . json_encode($history, true), 'error', true);
                    return show(config('code.error'), '服务异常');
                }
                $answerInfo = [
                    'uid' => $history['uid'],
                    'live_id' => $history['live_id'],
                    'live_record_id' => $history['live_record_id'],
                    'rid' => $history['rid'],
                    'rid2' => $history['rid2'],
                    'type' => $history['type'],
                    'price' => $history['price'],
                    'question' => $history['question'],
                    'question_des' => $history['question_des'],
                    'extend' => $history['extend'],
                ];
                break;
            case 20:
                $answerModel = new LiveAnswerDiceRecord();
                $history = $answerModel->getUserRequestAnswerPrepareInfo($liveId, $liveRecordId, $this->user['id']);
                if (!$history)
                {
                    Log::write('用户' . $this->user['id'] . 'dice解答申请信息未找到 - ' . json_encode($history, true), 'error', true);
                    return show(config('code.error'), '服务异常');
                }
                $divinationModel = new Divination();
                $diceInfo = $divinationModel->getDetail(['id' => $history['history_id']]);
                if (!$diceInfo)
                {
                    Log::write('用户' . $this->user['id'] . '骰子记录未找到 - ' . $history['history_id'], 'error', true);
                    return show(config('code.error'), '服务异常');
                }
                $answerInfo = [
                    'uid' => $history['uid'],
                    'live_id' => $history['live_id'],
                    'live_record_id' => $history['live_record_id'],
                    'history_id' => $history['history_id'],
                    'price' => $history['price'],
                    'question' => $diceInfo['question'],
                ];
                break;
            case 21:
                $answerModel = new LiveAnswerTarotRecord();
                $history = $answerModel->getUserRequestAnswerPrepareInfo($liveId, $liveRecordId, $this->user['id']);
                if (!$history)
                {
                    Log::write('用户' . $this->user['id'] . 'tarot解答申请信息未找到 - ' . json_encode($history, true), 'error', true);
                    return show(config('code.error'), '服务异常');
                }
                $tarotRecordModel = new ZlTarotRecords();
                $tarotInfo = $tarotRecordModel->getInfoById($history['history_id']);
                if (!$tarotInfo)
                {
                    Log::write('用户' . $this->user['id'] . '塔罗记录未找到 - ' . $history['history_id'], 'error', true);
                    return show(config('code.error'), '服务异常');
                }
                $answerInfo = [
                    'uid' => $history['uid'],
                    'live_id' => $history['live_id'],
                    'live_record_id' => $history['live_record_id'],
                    'history_id' => $history['history_id'],
                    'price' => $history['price'],
                    'question' => $tarotInfo['question'],
                ];
                break;
            default:
                $history = [];
                break;
        }
        //获取商品信息
        $goodsTypeInfo = (new Goods())->GoodsTypeInfo($orderType);
        $goodsInfo = current($goodsTypeInfo);
        //获取当前解答价格
        $price = $history['price'];
        //生成申请
        if (isset($answerInfo))
        {
            $answerId = $answerModel->addAnswerRequest($answerInfo);
        }

        //获取订单类型和描述语和订单编号
        $orderIdInfo = OrdersLib::createOrderId($orderType);
        //下单使用的商户配置
        $accountInfo = OrdersLib::getOrderAccountType($orderIdInfo['order_id'], $tradeType);
        $param['account'] = $accountInfo['account'];

        $liveAnchorInfo = (new LiveAnchorInfo())->getInfoById($liveId, ['name', 'avatar', 'live_id']);
        //订单拓展字段
        $extend['live_info'] = [
            'live_id' => $liveId,
            'live_record_id' => $liveRecordId,
            'name' => $liveAnchorInfo['name'],
            'avatar' => $liveAnchorInfo['avatar'],
            'gname' => $goodsInfo['name'],
            'total_amount' => $price
        ];
        $extend['goods_info'] = [
            'gid' => [
                'type' => $goodsInfo['type'],
                'name' => $goodsInfo['name'],
                'price' => $price,
                'num' => 1
            ]
        ];
        //生成待支付订单
        $insert = [
            'order_type' => $orderType,
            'uid' => $this->user['id'],
            'gid' => $goodsInfo['id'],
            'order_id' => $orderIdInfo['order_id'],
            'reid' => 0,
            'fid' => $answerId ?? 0,//解答申请id
            'trade_type' => $tradeType,
            'total_amount' => $price,
            'create_time' => time(),
            'status' => 0,
            'env_type' => 8,
            'account' => $accountInfo['account'],
            'extend' => json_encode($extend, true)
        ];

        $oid = (new OrdersCacheModel())->SaveData($insert);

        //5分钟检测解答关闭入队
        PushQueue::CloseOrder($orderIdInfo['order_id'], 300);

        //更新申请 order_num,status
        if (isset($answerModel))
        {
            $answerModel->updateAnswerRequest(['id' => $answerId ?? 0, 'order_num' => $orderIdInfo['order_id']]);
        }

        if ($tradeType === 4)
        {
            //检测准币是否充足
            $liveAnchorInfo['live_record_id'] = $liveRecordId;
            OrdersCacheModelLib::checkCoinPayInfo($insert, '', 2, json_encode(['live_info' => $liveAnchorInfo], true),false);

            $data = [
                'id' => $answerId ?? 0,
                'trade_type' => $tradeType,
                'total_amount' => $price,
                'order_id' => $orderIdInfo['order_id'],
            ];
            #神策打点
            (new \app\common\service\Orders())->getSensorsTrackData($orderIdInfo['order_id'], 'buy_confirm');
            return show(config('code.success'), '下单成功', $data);
        }

        //支付订单
        $res = OrdersCacheModelLib::unifyPayOrder([
            'oid' => $oid,
            'trade_type' => $tradeType,
            'total_amount' => $price,
            'pay_des' => $orderIdInfo['pay_des'],
            'order_id' => $orderIdInfo['order_id'],
            'openid' => '',
            'callback_url' => '',
            'order_type' => $orderType

        ], 1);

        if ($res['status'])
        {
            $data = $res['data'];
            $data['trade_type'] = $tradeType;
            $data['total_amount'] = $price;
            $data['id'] = $answerId ?? 0;
            #神策打点
            (new \app\common\service\Orders())->getSensorsTrackData($orderIdInfo['order_id'], 'buy_confirm');
            return show(config('code.success'), '下单成功', $data);
        }
        return show(config('code.error'), '下单失败');
    }
}
